package com.shy.db.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shy.api.model.query.MerchTradeQuery;
import com.shy.db.entity.UserPayConfig;
import com.shy.db.entity.UserPayInfo;
import com.shy.db.mapper.UserPayConfigMapper;
import com.shy.db.mapper.UserPayInfoMapper;
import com.shy.db.service.TradeService;
import com.shy.util.SignUtil;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class TradeServiceImpl implements TradeService {
    @Resource
    private UserPayConfigMapper userPayConfigMapper;
    @Resource
    private UserPayInfoMapper payInfoMapper;

    @Override
    public void checkSignQueryPayInfo(MerchTradeQuery merchTradeQuery) {
        //查询user_pay_config 获取app_sercret
        QueryWrapper<UserPayConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_no", merchTradeQuery.getUserNo()).eq("product_code", merchTradeQuery.getPayProductCode());
        UserPayConfig userPayConfig = userPayConfigMapper.selectOne(queryWrapper);
        if (userPayConfig == null) {
            throw new RuntimeException("商户支付配置不存在");
        }
        String appSecret = userPayConfig.getAppSecret();
        boolean checkSign = SignUtil.checkSign(merchTradeQuery, appSecret);
        if (!checkSign){
            throw new RuntimeException("签名失败");
        }
        //验证第三方支付信息
        QueryWrapper<UserPayInfo> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_no",merchTradeQuery.getUserNo()).eq("product_code",merchTradeQuery.getPayProductCode()).eq("pay_way_code",merchTradeQuery.getWayCode());
        UserPayInfo userPayInfo = payInfoMapper.selectOne(queryWrapper1);
        if( userPayInfo == null ){
            throw new RuntimeException("用户第三方配置错误");
        }

        String payConfig = userPayInfo.getPayConfig();
        if(StrUtil.isBlank(payConfig)){
            throw new RuntimeException("用户第三方配置错误");
        }
    }
}
